/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

/**
 *
 * @author Zhilin
 */
public class HighlightRender implements TableCellRenderer {

    String keyword = null;
    final Highlighter.HighlightPainter painter;
    final static Color HILIT_COLOR = Color.PINK;

    public HighlightRender(String keyword) {
        this.keyword = keyword;
        painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {

        String str = (String) value;
        JTextArea field = new JTextArea(str);
        try{
            field.setRows(str.length()/30);
        }catch(Exception e){
            field.setRows(0);
        }
        
        field.setText(str);
        field.setBorder(javax.swing.BorderFactory.createLineBorder(Color.BLACK));
        field.setLineWrap(true);
        field.setWrapStyleWord(true);
        field.setFont(new Font("Serif", Font.BOLD, 16));
       
        

        //field.setPreferredSize(new Dimension(field.getColumns()*50,field.getRows()*50));
        
        if (isSelected) {
            field.setBackground(table.getSelectionBackground());
        } else {
            field.setBackground(table.getBackground());
        }
        
        if(str == null || this.keyword == null) return field;
        if(str.isEmpty() || this.keyword.isEmpty()) return field;
        
        Highlighter hilit = new DefaultHighlighter();
        field.setHighlighter(hilit);
        
        String keyword_lower = keyword.toLowerCase();
        String str_lower = str.toLowerCase();
        
        int start = str_lower.indexOf(keyword_lower);
        while (start < str_lower.length()) {
            start = str_lower.indexOf(keyword_lower,start);
            if(start < 0) break;
            int end = start + keyword_lower.length();
            try {
                hilit.addHighlight(start, end, painter);
            } catch (BadLocationException ex) {
                Logger.getLogger(HighlightRender.class.getName()).log(Level.SEVERE, null, ex);
            }
            start = end + 1;
        }
        return field;
    }
}
